package com.yunduansing.core.interceptor;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yunduansing.core.model.SysUser;
import com.yunduansing.core.service.RoleService;
import com.yunduansing.core.service.impl.RoleServiceImpl;

/**
 * 登录拦截器
 * @author yunduansing
 *
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private RoleService service;
	
	private Logger log=LoggerFactory.getLogger(AuthInterceptor.class);
	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	//在控制器方法调用前执行
    //返回值为是否中断，true,表示继续执行（下一个拦截器或处理器）
    //false则会中断后续的所有操作，所以我们需要使用response来响应请求
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String uri=request.getRequestURI();
		log.info("uri:"+uri);
		log.info("登陆拦截"+format.format(new Date()));
		if(uri.contains("/account/login")){
			if(request.getSession().getAttribute("CurrentUser")!=null){
				//已登录则访问后台首页
				response.sendRedirect("manager/index/index");
			}else
				return true;
		}
		if(request.getSession().getAttribute("CurrentUser")!=null){
			return true;
		}
		response.sendRedirect(request.getContextPath()+"/manager/account/login");
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		String menuUrl=request.getRequestURI();
		System.out.println("uri："+menuUrl);
		if(request.getSession().getAttribute("CurrentUser")!=null&&menuUrl.contains("index")){
			SysUser user=(SysUser) request.getSession().getAttribute("CurrentUser");
			for(Integer item:user.getRoleIds()){
				System.out.println("角色"+item);
			}
			if(user.getRoleIds().size()>0){
				String btnCodes=service.getButtonCodeByMenuUrl(user.getRoleIds(), menuUrl.replace(request.getContextPath(), ""));
				modelAndView.addObject("btnCodes", btnCodes);
				System.out.println(menuUrl+" 按钮："+btnCodes);
			}else{
				modelAndView.addObject("btnCodes", "");
			}
		}
	}

}
